using IQIGame.Onigao.GamePlay;

namespace IQIGame.Onigao.Logic
{
    /// <summary>
    /// 呼叫电梯（注意呼叫电梯执行只能用于非乘坐模式）
    /// 参数组1：1：电梯tag，2：类型（1全量，2增量）3：全量：目标楼层（-1代表电梯门所在楼层，但限定电梯门触发），增量（目标楼层=当前楼层+增量）
    /// </summary>
    public class ExecCallElevator : BaseServiceExecution
    {
        public override void Execute(LevelRegion region, LevelPlayer player)
        {
            if (triggerEntity?.GetDynamicParam(EntityDynamicParamType.Elevator) != null)
            {
                LogicLog.LogError("电梯自身不能执行【呼叫电梯】服务（type：21），以避免【使用电梯】（type：13）与其混用（验证方式不用）。");
                return;
            }

            var config = _config as ExecParamCallElevator;
            if (!config.tagOrMcid.TryGetValue(triggerEntity, out int tagOrMcid))
            {
                LogicLog.LogError("无法获取到tagOrMcid.");
                return;
            }
            int type = config.type;
            int param3 = config.param;

            LevelEntity elevator = region.GetEntityByTagOrMcid(tagOrMcid);
            if (elevator == null || !elevator.HasDynamicParam(EntityDynamicParamType.Elevator))
            {
                LogicLog.LogError($"找不到指定实体或指定实体并非电梯。实体mcid{elevator?.entityConfig?.id}");
                return;
            }
            if (region.IsRunningElevator(elevator.id))
            {
                return;
            }

            EntityPropElevator elevatorProp = elevator.GetDynamicProperty(EntityDynamicPropertyType.Elevator) as EntityPropElevator;

            int targetFloor = 0;
            if (type == 1)
            {
                //如果目标楼层是-1，需要从电梯门上获取楼层
                if (param3 == -1)
                {

                }
                else
                {
                    targetFloor = param3;
                }
            }
            else
            {
                targetFloor = elevatorProp.curFloor + param3;
                if (targetFloor < 0)
                    targetFloor = 0;
                if (targetFloor >= elevatorProp.floorActiveList.Length)
                    targetFloor = elevatorProp.floorActiveList.Length - 1;
            }

            bool[] activeFloors = elevatorProp.floorActiveList;
            if (targetFloor > activeFloors.Length || !activeFloors[targetFloor])
            {
                LogicLog.LogError($"目标楼层非法或楼层未激活。目标楼层：{targetFloor}。");
                return;
            }

            region.StartElevator(player, elevator, targetFloor, false);
        }
    }
}
